import request from "./request";
// import { huonsecui } from './request';

function muionui() {
  let url = window.location.href;
  if (url.split("?")[2]) {
    let params = url.split("?")[2];
    let paramsObj = {};
    console.log('params', params)
    if (params) {
      let paramsArr = params.split("&");
      for (let i = 0; i < paramsArr.length; i++) {
        let param = paramsArr[i].split("=");
        paramsObj[param[0]] = param[1];
      }
    }
    return paramsObj["authCode"]
  } else if (url.split("?")[1]) {
    let params = url.split("?")[1];
    let paramsObj = {};
    console.log('params', params)
    if (params) {
      let paramsArr = params.split("&");
      for (let i = 0; i < paramsArr.length; i++) {
        let param = paramsArr[i].split("=");
        paramsObj[param[0]] = param[1];
      }
    }
    console.log('paramsObj["authCode"]', paramsObj["authCode"])
    // 链接地址的code
    return paramsObj["authCode"]
  }
}

// 正式免登录获取take
export function huonese() {
  return new Promise((resolve, reject) => {
    const obj = {
      authCode: muionui(),
    };
    console.log(muionui())
    let data = muionui()
    getWxUserAndMd(data).then((res) => {
      // console.log(res);
      sessionStorage.setItem("code", muionui());
      //判断调用免登的接口
      if (res.data.username != null) {
        const obj = JSON.stringify({
          avatar: res.data.avatar,
          phone: res.data.phone,
          username: res.data.username,
          openId: res.data.openId,
          fcProjectId: res.data.fcProjectId,
        })
        getMdToken(obj).then((res) => {
          alert(`res.data.token：${res.data.token}`)
          if (res.data.token != undefined) {
            // 保存本地缓存
            sessionStorage.setItem("token", res.data.token);
            resolve('ok')
          } else {
            reject('err')
            console.error("获取token失败");
          }
        })
      } else {
        resolve('ok')
        console.log("getToken返回为空");
      }
    });
  })
}

// 拿到code获取用户信息
export function getWxUserAndMd(data) {
  return request({
    url: '/userInfo/fwm/getToken?authCode=' + data,
    method: 'post',
  })
}

// 免登获取take的接口
function getMdToken(obj) {
  // return huonsecui({
  //   url: '/phoneloginMd',
  //   method: 'post',
  //   data
  // })
  return request({
    url: '/phoneloginMd',
    method: 'post',
    dataType: 'json',
    headers: {
      "Content-Type": "application/json",
    },
    data: obj
  })
}

// 获取用户信息
// export function getinofp() {
//     return instance_api({
//         url: judgeNetworkState() + '/getInfo',
//         method: 'get',
//     })
// }

// 测试获取take的接口
// export function phoneloginAndPerInfo(data) {
//     return huonsecui({
//         url: '/phonelogin',
//         method: 'post',
//         data
//     })
// }
